﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NetworkingController.cs" company="DissingNellemann">
//   
// All rights reserved </copyright>
// <summary>
//   The networking controller.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Website.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using Website.CRUDServices;
    using Website.Models;
    using Website.Models.Styling;
    using Website.Models.ViewModels;

    using User = Website.Models.Domain.User;

    /// <summary>
    ///     The networking controller.
    /// </summary>
    [Authorize(Roles = "User, Admin")]
    public class NetworkingController : BaseController
    {
        #region Public Methods and Operators

        /// <summary>
        ///     The get header items.
        /// </summary>
        /// <returns>
        ///     The list of headeritems for a networking view.
        /// </returns>
        public static List<TableViewHeaderItem> GetHeaderItems()
        {
            var headerItems = new List<TableViewHeaderItem>();
            var item1 = new TableViewHeaderItem { Text = "Dato", SortableName = "TimeOfActivity", IsSortable = true, };

            var item2 = new TableViewHeaderItem { Text = "Type", SortableName = string.Empty, IsSortable = false };
            var item3 = new TableViewHeaderItem { Text = "Beskrivelse", SortableName = "ProductType", IsSortable = true };
            var item4 = new TableViewHeaderItem { Text = "WT Rolle", SortableName = string.Empty, IsSortable = false };
            headerItems.Add(item1);
            headerItems.Add(item2);
            headerItems.Add(item3);
            headerItems.Add(item4);
            return headerItems;
        }

        /// <summary>
        /// The index.
        /// </summary>
        /// <param name="skip">
        /// The skip.
        /// </param>
        /// <param name="take">
        /// The take.
        /// </param>
        /// <param name="orderBy">
        /// The order by.
        /// </param>
        /// <param name="sortAscending">
        /// The sort ascending.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult Index(int? skip, int? take, string orderBy, bool? sortAscending)
        {
            this.Session["CurrentSubMenuSelection"] = "Networking";

            ListView<Activity> view = null;

            List<TableViewHeaderItem> headerItems = GetHeaderItems();

            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var query = new ActivityQuery();
                    query.Settings = new SearchSettings
                    {
                        SortAscending =
                            sortAscending ?? false,
                        Skip = skip ?? 0,
                        Take = take ?? 20,
                        OrderBy =
                            !string.IsNullOrEmpty(orderBy)
                                ? orderBy
                                : "TimeOfActivity"
                    };
                    query.HasNetworkActivity = true;

                    IResult iRes = client.Query(query);
                    if (iRes != null)
                    {
                        var res = (ActivityResult)iRes;
                        view = new ListView<Activity>(
                            res.List.ToList(),
                            skip ?? 0,
                            take ?? 20,
                            res.TotalRowCount,
                            query.Settings.OrderBy,
                            sortAscending ?? true,
                            headerItems,
                            "Index");

                        var uniquePresentations = new List<Guid>();
                        foreach (var pre in res.List.Select(x => x.NA.Presentations))
                        {
                            uniquePresentations.AddRange(pre.ToList());
                        }

                        this.ViewData["Presentations"] =
                            PrimitiveTypes.GetPresentationsWithIDs(uniquePresentations.Distinct());
                    }
                });

            this.ViewData["Locations"] = PrimitiveTypes.GetLocations();

            return View(view);
        }

        /// <summary>
        ///     The new network.
        /// </summary>
        /// <returns>
        ///     The <see cref="ActionResult" />.
        /// </returns>
        public ActionResult NewNetwork()
        {
            this.ViewData["CreateLocationActionName"] = "CreateLocationJson";
            this.ViewData["Presentations"] = PrimitiveTypes.GetPresentations();
            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();

            // grab profiles
            ProfilesView pv = ProfilesView.GetRelated();
            pv.SortAscending = true;
            pv.Skip = 0;
            pv.Take = 10000;
            pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            this.ViewData["Profiles"] = pv;
            return View();
        }

        /// <summary>
        /// The new network.
        /// </summary>
        /// <param name="datepicker">
        /// The datepicker.
        /// </param>
        /// <param name="location">
        /// The location.
        /// </param>
        /// <param name="ownerProjects">
        /// The owner projects.
        /// </param>
        /// <param name="attendees">
        /// The attendees.
        /// </param>
        /// <param name="na">
        /// The na.
        /// </param>
        /// <param name="andet">
        /// The andet.
        /// </param>
        /// <param name="commentary">
        /// The commentary.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        [HttpPost]
        [ValidateInput(false)] 
        public ActionResult NewNetwork(
            DateTime? datepicker,
            Guid location,
            List<Guid> ownerProjects,
            List<Guid> attendees,
            NetworkingActivity na,
            string andet,
            string commentary,
            string NetworkType,
            List<string> Roles
            )
        {
            // finish off NA part of the Activity
            na.ID = Guid.NewGuid();
            na.PresentationComment = andet;

            if (Roles != null && Roles.Any())
            {
                if (Roles.Contains("Attendance"))
                {
                    na.Attendance = true;
                }
                if (Roles.Contains("Booth"))
                {
                    na.Booth = true;
                }
                if (Roles.Contains("Organizer"))
                {
                    na.Organizer = true;
                }
            }

            switch (NetworkType)
            {
                case "IsNetworkingEvent":
                    na.IsNetworkingEvent = true;
                    na.IsConferenceEvent = false;
                    na.IsDelegationTravel = false;
                    na.IsProductLaunch = false;
                    break;
                case "IsConferenceEvent":
                    na.IsNetworkingEvent = false;
                    na.IsConferenceEvent = true;
                    na.IsDelegationTravel = false;
                    na.IsProductLaunch = false;
                    break;
                case "IsDelegationTravel":
                    na.IsNetworkingEvent = false;
                    na.IsConferenceEvent = false;
                    na.IsDelegationTravel = true;
                    na.IsProductLaunch = false;
                    break;
                case "IsProductLaunch":
                    na.IsNetworkingEvent = false;
                    na.IsConferenceEvent = false;
                    na.IsDelegationTravel = false;
                    na.IsProductLaunch = true;
                    break;
            }

            // fill out the superclass
            var act = new Activity
            {
                Attendees = (attendees ?? new List<Guid>()).ToArray(),
                NA = na,
                OwnerProjects = (ownerProjects ?? new List<Guid>()).ToArray(),
                Commentary = commentary,
                ID = Guid.NewGuid(),
                Location = location,
                TimeOfActivity = datepicker,
                Creator = (this.Session["LoggedInUser"] as User).ID
            };

            // save it!
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var cmd = new CreateActivityCommand { Dto = act };
                    client.ExecuteCommand(cmd);
                });

            return this.RedirectToAction("Index");
        }

        public ActionResult UpdateNetwork(Guid id)
        {
            this.ViewData["CreateLocationActionName"] = "CreateLocationJson";
            this.ViewData["Presentations"] = PrimitiveTypes.GetPresentations();
            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();

            // grab profiles
            ProfilesView pv = ProfilesView.GetRelated();
            pv.SortAscending = true;
            pv.Skip = 0;
            pv.Take = 10000;
            pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            this.ViewData["Profiles"] = pv;

            // load object for editing
            var dto = new Activity();
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var query = new ActivityQuery { Settings = new SearchSettings { IDEquals = id } };

                    var res = client.Query(query) as ActivityResult;
                    if (res != null)
                    {
                        if (res.List.Any())
                        {
                            dto = res.List[0];
                        }
                    }
                });

            // ensure we have some content
            if (dto != null)
            {
                return View(dto);
            }

            // something buggered up. Better send them back to the index.
            return this.RedirectToAction("Index");

        }

        [HttpPost]
        [ValidateInput(false)] 
        public ActionResult UpdateNetwork(
            Guid ID,
            Guid ID2,
            DateTime? datepicker,
            Guid location,
            List<Guid> ownerProjects,
            List<Guid> attendees,
            NetworkingActivity na,
            string andet,
            string commentary,
            string NetworkType,
            List<string> Roles
            )
        {
            // finish off NA part of the Activity
            na.ID = ID2;
            na.PresentationComment = andet;

            if(Roles != null && Roles.Any()){
                if (Roles.Contains("Attendance"))
                {
                    na.Attendance = true;
                }
                if (Roles.Contains("Booth"))
                {
                    na.Booth = true;
                }
                if (Roles.Contains("Organizer"))
                {
                    na.Organizer = true;
                }
            }

            switch (NetworkType)
            {
                case "IsNetworkingEvent":
                    na.IsNetworkingEvent = true;
                    na.IsConferenceEvent = false;
                    na.IsDelegationTravel = false;
                    na.IsProductLaunch = false;
                    break;
                case "IsConferenceEvent":
                    na.IsNetworkingEvent = false;
                    na.IsConferenceEvent = true;
                    na.IsDelegationTravel = false;
                    na.IsProductLaunch = false;
                    break;
                case "IsDelegationTravel":
                    na.IsNetworkingEvent = false;
                    na.IsConferenceEvent = false;
                    na.IsDelegationTravel = true;
                    na.IsProductLaunch = false;
                    break;
                case "IsProductLaunch":
                    na.IsNetworkingEvent = false;
                    na.IsConferenceEvent = false;
                    na.IsDelegationTravel = false;
                    na.IsProductLaunch = true;
                    break;
            }

            // fill out the superclass
            var act = new Activity
            {
                Attendees = (attendees ?? new List<Guid>()).ToArray(),
                NA = na,
                OwnerProjects = (ownerProjects ?? new List<Guid>()).ToArray(),
                Commentary = commentary,
                ID = ID,
                Location = location,
                TimeOfActivity = datepicker,
                Creator = (this.Session["LoggedInUser"] as User).ID
            };

            // save it!
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var cmd = new UpdateActivityCommand { Dto = act };
                    client.ExecuteCommand(cmd);
                });

            return this.RedirectToAction("Index");
        }


        public ActionResult ViewNetwork(Guid id)
        {
            this.Init("Events");
            this.Session["SubMenuItems"] = ActivityController.CreateSubMenu();
            this.Session["CurrentSubMenuSelection"] = "Networking";

            this.ViewData["CreateLocationActionName"] = "CreateLocationJson";
            this.ViewData["Presentations"] = PrimitiveTypes.GetPresentations();
            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();

            // grab profiles
            ProfilesView pv = ProfilesView.GetRelated();
            pv.SortAscending = true;
            pv.Skip = 0;
            pv.Take = 10000;
            pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            this.ViewData["Profiles"] = pv;

            // load object for editing
            var dto = new Activity();
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var query = new ActivityQuery { Settings = new SearchSettings { IDEquals = id } };

                    var res = client.Query(query) as ActivityResult;
                    if (res != null)
                    {
                        if (res.List.Any())
                        {
                            dto = res.List[0];
                        }
                    }
                });

            // ensure we have some content
            if (dto != null)
            {
                return View(dto);
            }

            // something buggered up. Better send them back to the index.
            return this.RedirectToAction("Index");

        }

        public ActionResult DeleteNA(Guid id)
        {
            CRUDServiceProvider.WithCRUDService(client =>
            {
                CRUDServices.DeleteActivityCommand cmd = new DeleteActivityCommand() { Dto = id };
                client.ExecuteCommand(cmd);
            });

            return RedirectToAction("Index");
        }

        #endregion
    }
}